/*
 * @Description: 
 * @Author: chendingfengmail@163.com
 * @Date: 2021-12-29 09:43:22
 * @LastEditTime: 2021-12-31 09:04:43
 * @LastEditors: chendingfengmail@163.com
 * @Reference: 
 */
import RegionData from '@/commons/region/regionData.js'

const region = {}

region.root = {
  code: '440604',
  level: 3,
  name: '禅城区',
  parentCode: '440600',
  childs: []
}

/**
 * 通过区域节点code获取区域路径
 * @param {String} code 区域节点code
 * @returns 
 */
region.getRegionPath = function (code) {
  var regionName = '';
  var regionList = RegionData.regionList;
  var names = [];
  function findRegion(code) {
    regionList.forEach(item => {
      if (item.code == code) {
        names.unshift(item.name);
        if (item.code != region.root.code && item.level > 0) {
          findRegion(item.parentCode);
        }
      }
    });
  }
  findRegion(code);
  regionName = names.join(' / ');
  return regionName;
}

/**
 * 通过区域节点code获取以code为根节点的区域树
 * @param {String} code 区域节点code
 * @returns 
 */
region.findRegionTreeByCode = function (code) {
  let findForFn = function (code, nodes, path) {
    if (path === undefined) {
      path = {};
    }
    for (var i = 0; i < nodes.length; i++) {
      var tmpPath = path;
      if (code == nodes[i].code) {
        tmpPath = nodes[i];
        return tmpPath;
      }
      if (nodes[i].childs) {
        var findResult = findForFn(code, nodes[i].childs, tmpPath);
        if (findResult) {
          return findResult;
        }
      }
    }
  }

  return [findForFn(code, RegionData.regionTree)]
}

/**
 * 通过树结构数据获取所有节点的code
 * @param {treeArr} treeData 
 */
region.findRegionTreeDataCodes = function (treeData) {
  let codes = []
  let findForFn = function (treeData, path) {
    if (path === undefined) {
      path = {};
    }
    for (var i = 0; i < treeData.length; i++) {
      var tmpPath = path;
      if (treeData[i].level != -2 && treeData[i].level != -1) {
        codes.push(treeData[i].code)
      }
      if (treeData[i].childs) {
        findForFn(treeData[i].childs, tmpPath);
      }
    }
  }
  findForFn(treeData)
  return codes;

}

export default region;
